package com.ziyia.httpurlconnectiontest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private final int REQUEST = 1;
    private EditText response;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        response = findViewById(R.id.response);
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case REQUEST:
                    String result = (String) msg.obj;
                    response.setText(result);
                    break;
            }

        }
    };


    public void request(View view) {
        Runnable runnable = () -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL("http://ziyia.cn");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                InputStream inputStream = connection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    buffer.append(line);
                }

                Message message = new Message();
                message.what = REQUEST;
                message.obj = buffer.toString();
                handler.sendMessage(message);

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                connection.disconnect();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
}